<?php
namespace App\Services;
use App\Exceptions\ServiceException;
use App\Models\Customer;
use App\Models\SimulationLogin;
use App\DTOS\Admin\SimulationLoginSearchDTO;
use App\DTOS\Admin\SimulationLoginInsertDTO;
use App\DTOS\Admin\SimulationLoginUpdateDTO;
// 模拟登录
class SimulationLoginService
{
    /**
    * @var  \Illuminate\Database\Eloquent\Builder
    */
    private SimulationLogin $model;

    public function __construct()
    {
        $this->model = new SimulationLogin;
        global $gameArea;
        $this->model->setGameArea($gameArea);
    }

    public function paginate(SimulationLoginSearchDTO $DTO)
    {
        $perPage = $DTO->getLimit();
        $page = $DTO->getPage();
        $model = $this->model;
        /**条件判断**/
        return $model->orderByDesc("id")->paginate($perPage,'*','page',$page);
    }

    /**
    * @param  SimulationLoginInsertDTO $insertDTO
    * @return  int
    */
    public function insert(SimulationLoginInsertDTO $insertDTO){
        $data = $insertDTO->toArray();
        unset($data['page']); unset($data['limit']);
        foreach($data as &$value){
            if (is_array($value)){
                $value= json_encode(array_values($value));
            }
        }
        $data['created_at'] = now();
        $formId = $insertDTO->getFromId();
        $customer = Customer::query()->find((int)$formId);
        if (!$customer){
            throw new ServiceException('被登录者不存在');
        }
        if ($customer->channel_type==1){
          throw new ServiceException('官方渠道的账号无需模拟登录');
        }

        return $this->model->insertGetId($data);
    }

    /**
    * @param  int $id
    * @param  SimulationLoginUpdateDTO $updateDTO
    */
    public function updateById($id,SimulationLoginUpdateDTO $updateDTO)
    {
        $data = $updateDTO->toArray();
        unset($data['page']); unset($data['limit']);
        foreach($data as &$value){
            if (is_array($value)){
                $value= json_encode(array_values($value));
            }
        }
        $data['updated_at'] = now();
        $this->model->where('id',$id)->update($data);
    }

    public function deleteById($id)
    {
        $this->model->where('id',$id)->delete();
    }

    public function deleteByIds($ids)
    {
        if (empty($ids)) return;
        $this->model->whereIn('id',$ids)->delete();
    }
    public function getById($id)
    {
        return $this->model->where('id',$id)->first();
    }
}
